<template>
  <div class="container mt-5">
    <h1 class="mb-4">To-Do List</h1>
    <TaskForm :task-to-edit="taskToEdit" @task-created="fetchTasks" @task-updated="fetchTasks" @cancel-edit="cancelEdit" />
    <TaskList :tasks="tasks" @task-updated="fetchTasks" @task-deleted="fetchTasks" @edit-task="startEdit" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import TaskForm from '../components/TaskForm.vue';
import TaskList from '../components/TaskList.vue';
import { getTasks } from '../api';

const tasks = ref([]);
const taskToEdit = ref(null);

const fetchTasks = async () => {
  try {
    const response = await getTasks({ per_page: 10 });
    tasks.value = response.data.data;
    taskToEdit.value = null;
  } catch (error) {
    console.error('获取任务失败:', error);
  }
};

const startEdit = (task) => {
  taskToEdit.value = { ...task };
};

const cancelEdit = () => {
  taskToEdit.value = null;
};

onMounted(() => {
  fetchTasks();
});
</script>